package com.rede.didiok.user.modulelist.file.service.impl;

import java.io.File;
import java.io.IOException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import com.rede.didiok.common.dto.admin.SystemConfigDto;
import com.rede.didiok.common.exception.exceptionType.BusinessException;
import com.rede.didiok.common.utils.DateUtils;
import com.rede.didiok.common.utils.FileUtils;
import com.rede.didiok.user.modulelist.file.annotation.UploadType;
import com.rede.didiok.user.modulelist.file.entity.FileCategoryEntity;
import com.rede.didiok.user.modulelist.file.enums.UploadTypeEnum;
import com.rede.didiok.user.modulelist.file.util.AliyunOssUtil;


@Service
@RefreshScope
@Slf4j
@UploadType({UploadTypeEnum.ALIOSS_UPLOAD})
public class AliOssServiceImpl extends AbstractUploadFile {

    @Autowired
    AliyunOssUtil aliyunOssUtil;


    @Override
    public String uploadFile(SystemConfigDto systemConfig, File tempFile, FileCategoryEntity fileSort, String newFileName) {
        try {
            String sortUrl = org.apache.commons.lang3.StringUtils.defaultIfEmpty(fileSort.getUrl(), "base/common/");
            //获取新文件名 【根据扩展名保存】
            String uploadDir = sortUrl + "/" + FileUtils.getPicExpandedName(newFileName) +"/" + DateUtils.getYears() + "/"
                    + DateUtils.getMonth() + "/" + DateUtils.getDay() + "/" + newFileName;
            return aliyunOssUtil.uploadFile(systemConfig, tempFile, uploadDir.substring(1));
        } catch (IOException e) {
            log.error("阿里云上传文件失败:", e);
            throw new BusinessException("阿里云上传文件失败");
        }
    }

    @Override
    public String deleteFile(String fileName, SystemConfigDto systemConfig) {
        return aliyunOssUtil.deleteFile(fileName, systemConfig);
    }

}
